import SparkMD5 from 'spark-md5'

self.onmessage = async e => {
  const { fileChunks } = e.data
  const spark = new SparkMD5.ArrayBuffer()

  let count = 0
  const totalChunks = fileChunks.length

  for (let i = 0; i < totalChunks; i++) {
    const chunk = fileChunks[i]

    try {
      const arrayBuffer = await readFileChunk(chunk)
      spark.append(arrayBuffer)

      count++
      
      self.postMessage({
        progress: Math.floor((count / totalChunks) * 100),
        hash: null
      })
    } catch (error) {
      self.postMessage({
        error: `读取文件分片失败: ${error.message}`,
        progress: Math.floor((count / totalChunks) * 100)
      })
    }
  }

  self.postMessage({
    progress: 100,
    hash: spark.end()
  })
}

// 分片转二进制（计算 Hash 所需要）
const readFileChunk = chunk => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = e => resolve(e.target.result)
    reader.onerror = e => reject(e.target.error)
    reader.readAsArrayBuffer(chunk)
  })
}
